#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cansetmodel.h"

#include <QDebug>
#include <QMessageBox>
#include <QDateTime>
#include <stdint.h>
#include <zlgcan.h>
#include <QFile>
#include <QFileDialog>
#include <QListWidget>
#include <QListView>
#include <QTableWidget>
#include <QStandardItem>

static const DeviceInfo kDeviceType[] =
{
    {"ZCAN_USBCAN1",ZCAN_USBCAN1, 1},
    {"ZCAN_USBCAN2",ZCAN_USBCAN2, 2},
    //    {"ZCAN_USBCAN_E_U",ZCAN_USBCAN_E_U, 1},
    //    {"ZCAN_USBCAN_2E_U",ZCAN_USBCAN_2E_U, 2},
    //    {"ZCAN_USBCANFD_200U",ZCAN_USBCANFD_200U, 2},
    //    {"ZCAN_USBCANFD_100U",ZCAN_USBCANFD_100U, 1},
    //    {"ZCAN_USBCANFD_MINI",ZCAN_USBCANFD_MINI, 1},
};

static const BaudRateInfo kBaudRateInfo[] =
{
    {"1000Kbps","1000000"},
    {"500Kbps","500000"},
    {"250Kbps","250000"},
    {"125Kbps","125000"},

};


QDateTime currentTime = QDateTime::currentDateTime();
QString logName = "log_" + currentTime.toString("yyyyMMddhhmmss");
QFile *file = new QFile(QDir::currentPath() + "/" + logName);

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    for(int i=0; i<2; i++)
    {
        ui->comBox_DeviceType_2->addItem(kDeviceType[i].name);      //添加设备类型名称
    }

    for(int i=0; i<4; i++)
    {
        ui->comBox_BaudRate_2->addItem(kBaudRateInfo[i].name);      //添加波特率
    }

    QStringList strlistIndex;
    strlistIndex.clear();
    strlistIndex << tr("0") << tr("1");     //添加通道索引
    ui->comBox_DeviceIndex_2->clear();
    ui->comBox_DeviceIndex_2->addItems(strlistIndex);

    QStringList strlistFrame;
    strlistFrame.clear();
    strlistFrame << tr("标准帧") << tr("扩展帧");
    ui->comBox_FrameType->clear();
    ui->comBox_FrameType->addItems(strlistFrame);
    ui->Btn_connect_2->setCheckable(true);
    ui->Btn_connect_2->setStyleSheet("color: green");

    CanSet = new CanSetModel;       //can工作模式类设置对象

    myThread = new QThread(this);       //新建线程

    CanSet->moveToThread(myThread);    //将对象放入线程

    connect(this, &MainWindow::StartDataReceive, CanSet, &CanSetModel::DataReceive);    //窗口开始后接收数据信号触发canset对象接收数据

    connect(this,&MainWindow::destroyed,this,&MainWindow::CloseWin);    //主窗口销毁后，关闭线程和canset对象

    connect(CanSet,&CanSetModel::DataUpdata,this,&MainWindow::UpdataReceive);   //canset数据更新触发主窗口数据获取更新
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_Btn_connect_2_clicked()
{
    if(ui->Btn_connect_2->isChecked() == false)     //按钮标记切换
    {      
        ui->Btn_connect_2->setText("连接并启动");
        ui->Btn_connect_2->setStyleSheet("color: green");
        if(myThread->isRunning())
        {
            qDebug() << "myThread is running, quit it now" ;
            CanSet->CanClose();
            myThread->quit();
            myThread->wait();
        }
    }
    else
    {



        uint index = ui->comBox_DeviceType_2->currentIndex();     //获取can设备名称索引
        uint device_type = kDeviceType[index].device_type;      //获取设备名称
        uint deviceIndex = ui->comBox_DeviceIndex_2->currentIndex();      //获取设备通道索引
        uint br =  ui->comBox_BaudRate_2->currentIndex();     //获取设备波特率索引
        char* brv  = kBaudRateInfo[br].value.toLatin1().data();       //转化波特率格式，返回一个储存字节数组数据的指针

        CanSet->SetPara(device_type, deviceIndex, brv);     //设置can参数：can接口名称，设备通道索引,波特率

        bool isok = CanSet->CanConnect();     //连接can

        if(isok)
        {
            ui->Btn_connect_2->setText("断开连接");
            ui->Btn_connect_2->setStyleSheet("color: red");
            myThread->start();

            emit this->StartDataReceive();
        }
    }
}

void MainWindow::UpdataReceive(CanDataBase *cdb)
{
    QString  str;
    str += cdb->IsSend?"发送 ":"接收 ";
    // str += QString::number(cdb->sTime,'f',6);
    str += cdb->Time.toString("HH:mm:ss.zzz");
    str += "  ID:0x";
    str += QString::number(cdb->Id,16);
    str += cdb->IsExtendFrame?" 扩展帧 ":" 标准帧 ";
    str += " 数据：";
    str += cdb->StrData;



    while (!file->open(QIODevice::WriteOnly | QIODevice::Append));
    {
        QTextStream txtOutput(file);
        txtOutput << str << endl;
        file->close();
    }

    QListWidgetItem *item = new QListWidgetItem(str);    

    if(cdb->IsSend)
    {
        item->setForeground(Qt::red);
    }


    ui->listView_reseive->addItem(item);
    ui->listView_reseive->scrollToBottom();     //显示列表滚动到底

    if(ui->listView_reseive->count() >= 50)     //显示列表中超过50行后，第一行进行删除处理
    {
        ui->listView_reseive->removeItemWidget(ui->listView_reseive->takeItem(0));
    }
}


void MainWindow::CloseWin()
{
    if(myThread->isRunning())
    {
        CanSet->CanClose();
        ui->Btn_connect_2->setText("连接并启动");
        myThread->quit();
        myThread->wait();

        delete CanSet;
    }
}


void MainWindow::on_Btn_clean_2_clicked()
{
    ui->listView_reseive->clear();      //删除显示列表内容
}
